package com.etrans.web.gps.business.evidence.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.egov.base.impl.ImgHelper;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.evidence.domain.MPictureVo;
import com.etrans.web.gps.business.evidence.domain.PictureVO;
import com.etrans.web.gps.business.report.domain.HistoryImgVO;
import com.etrans.web.gps.business.report.domain.HistoryPicChart;
import com.etrans.web.gps.business.report.domain.HistoryPicVO;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.util.Config;
//import com.etrans.web.gps.util.EcpmUtil;
import com.etrans.web.gps.util.map.GpsToGaoDe;
import com.mongodb.QueryOperators;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.And;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.ValidationEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PictureService extends BaseService {

    /*  @Autowired
      private EcpmUtil ecpmUtil;*/
    @Autowired
    private Config config; // 引用统一的参数配置类

    // private static String imgPrefix  = "";

    /**
     * 车辆图片统计
     *
     * @param vehicleID
     * @param startTime
     * @param endTime
     * @return
     */
    public List<HistoryImgVO> queryPictureListByVehicleId(String vehicleID, String startTime, String endTime, String enterprisseId, String eventCode) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //处理查询条件
        HashMap<String, Object> whereMap = new HashMap<>();
        HashMap<String, Object> whereMap_Time = new HashMap();
        List<PictureVO> pictureImgList = new ArrayList<>();
        if (null != vehicleID && !"".equals(vehicleID)) {
            List<Integer> tempVehicleIds = new ArrayList<>();
            Map<String, Object> tempParamsIds = new HashMap<>();
            if (vehicleID.contains(",")) {
                String[] StringArrayIds = vehicleID.split(",");
                for (int i = 0; i < StringArrayIds.length; i++) {
                    tempVehicleIds.add(Integer.valueOf(StringArrayIds[i]));
                }
            } else {
                tempVehicleIds.add(Integer.valueOf(vehicleID));
            }
            tempParamsIds.put(QueryOperators.IN, tempVehicleIds);
            whereMap.put("vehicle_id", tempParamsIds);
        }
        try {
            if (null != startTime && !"".equals(startTime)) {
                whereMap_Time.put("$gte", format.parse(startTime));    //大于
            }
            if (null != endTime && !"".equals(endTime)) {
                whereMap_Time.put("$lte", format.parse(endTime));        //小于
            }
            whereMap.put("gps_time", whereMap_Time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //排序
        HashMap<String, Object> sortMap = new HashMap<>();
        sortMap.put("gps_time", -1);
        List<HistoryImgVO> pics = MGTemplete.find("egov", "img_info", whereMap, 20, sortMap, HistoryImgVO.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (HistoryImgVO picVo : pics) {
            picVo.setGpsTimeStr(sdf.format(picVo.getGps_time()));
            picVo.setImgUrl(config.imagePath + ImgHelper.getImageFileName(picVo.getVehicle_id(), picVo.getLens_id(), picVo.getGps_time().getTime()));
        }
        return pics;
    }

    // 状态解析

    public String getStatusStr(int terminalKind, String status) {
        String vehicleStatus = "";
        if (status != null && !"".equals(status)) {
            //Map<Integer, Boolean> tempMap = ecpmUtil.decodeStatus(terminalKind, status);
            Map<Integer, Boolean> tempMap = new HashMap<>();
            if (tempMap.isEmpty()) {
                return vehicleStatus;
            }
            int[] strStatus = {0, 1, 9, 10, 11, 12, 13, 17, 18};
            String[] strStatusName = "ACC,是否定位,前门,后门,车门,发动机,空调,远光灯,近光灯".split(",");
            for (int j = 0; j < strStatus.length; j++) {
                if (j == 0) {
                    if (tempMap.get(strStatus[j])) {
                        vehicleStatus = strStatusName[j] + "开";
                    } else {
                        vehicleStatus = strStatusName[j] + "关";
                    }
                } else if (j == 1) {
                    if (tempMap.get(strStatus[j])) {
                        vehicleStatus = vehicleStatus + "," + "精确";
                    } else {
                        vehicleStatus = vehicleStatus + "," + "盲区";
                    }
                } else {
                    if (tempMap.get(strStatus[j])) {
                        vehicleStatus = vehicleStatus + "," + strStatusName[j] + "开";
                    } else {
                        vehicleStatus = vehicleStatus + "," + strStatusName[j] + "关";
                    }
                }
            }
        }
        return vehicleStatus;
    }

    /**
     * 获取图片存储的文件名 <br>
     * 格式：<文件服务指定目录>/image/<yyyy>/<yyyy-MM-dd>/<终端ID倒数3-4位>/<终端ID倒数1-2位>/<文件名> <br>
     * <文件名>格式：<8位终端ID>.<通道号>.<yyyy-MM-dd-HH-mm-ss>.jpg <br>
     * 例：/u06/somePath/image/2015/2015-03-26/32/91/00283291.01.2015-03-26-22-15-00.jpg
     *
     * @param terminalId 终端编号
     * @param cameraNo   摄像头号
     * @param gpsTime    定位时间
     * @return 文件名
     */
    protected String formatImageFilename(int terminalId, int cameraNo, Date gpsTime, String flag) {
        String strTerminalId = String.format("%08d", terminalId);
        Calendar time = Calendar.getInstance();
        time.setTime(gpsTime);
        int year = time.get(Calendar.YEAR);
        int month = time.get(Calendar.MONTH) + 1;
        int day = time.get(Calendar.DAY_OF_MONTH);
        int hour = time.get(Calendar.HOUR_OF_DAY);
        int minute = time.get(Calendar.MINUTE);
        int second = time.get(Calendar.SECOND);

        return String.format("image/%04d/%04d-%02d-%02d/%s/%s/%s.%02d.%04d-%02d-%02d-%02d-%02d-%02d.mp4", year, year,
                month, day, strTerminalId.substring(4, 6), strTerminalId.substring(6, 8), strTerminalId, cameraNo, year,
                month, day, hour, minute, second);

    }

    /**
     * 统计不同类型终端的报警，做不同类型终端报警的归类
     *
     * @param eList
     * @return
     */
    private List<String> addEventCode(List<String> eList) {
        String eventCode = eList.get(0);
        switch (eventCode) {
            case "4":  //打哈欠
                eList.add("51");
                break;
            case "5":  //打电话
                eList.add("60");
                break;
            case "6":  //抽烟
                eList.add("61");
                break;
            case "7":  //闭眼
                eList.add("50");
                break;
            case "8":  //注意力分散
                eList.add("62");
                break;
            case "9":  //急减速
                eList.add("65");
                break;
            case "10": //急加速
                eList.add("64");
                break;
            case "13": //车道偏离报警触发
                eList.add("41");
                eList.add("42");
                break;
            case "14": //前向碰撞报警触发
                eList.add("40");
                break;
            default:
                break;
        }


        return eList;
    }

    /**
     * 查询柱状图显示数据
     *
     * @param vehicleID
     * @param startTime
     * @param endTime
     * @param enterprisseId
     * @param eventCode
     * @return
     */
    public HistoryPicChart queryEvidenceChartData(Integer vehicleID, String startTime, String endTime, String enterprisseId, String eventCode) {

        HashMap<String, Object> whereMap = getParamFormatted(vehicleID, startTime, endTime, enterprisseId, eventCode);
        List<Object> historyImgList = MGTemplete.groupBy("egov", "img_info", whereMap, "vehicle_no", null, 0);
        List<String> barXAxisData = new ArrayList<>();
        List<Integer> barSeriesData = new ArrayList<>();
        List<String> vehicleIdList = new ArrayList<>();
        if (historyImgList.size() > 0) {
            for (Object obj : historyImgList) {
                String jsonStr = JSONObject.toJSONString(obj);
                JSONObject json = JSON.parseObject(jsonStr);
                String vehicle_no = String.valueOf(json.get("_id")).split(":")[0];
                String vehicleId = String.valueOf(json.get("vehicleId")).split(":")[0];
                barXAxisData.add(vehicle_no);
                barSeriesData.add(Integer.parseInt(String.valueOf(json.get("count"))));
                vehicleIdList.add(vehicleId);
            }
        }
        HistoryPicChart chart = new HistoryPicChart();
        chart.setxAxisData(barXAxisData);
        chart.setSeries(barSeriesData);
        chart.setVehicleIdList(vehicleIdList);
        return chart;
    }


    /**
     * description: 获取参数格式组装
     *
     * @param vehicleID
     * @param startTime
     * @param endTime
     * @param enterprisseId
     * @param eventCode
     * @return
     */
    public HashMap<String, Object> getParamFormatted(Integer vehicleID, String startTime, String endTime, String enterprisseId, String eventCode) {
        //处理查询条件
        HashMap<String, Object> whereMap = new HashMap<>();
        HashMap<String, Object> whereMap_Time = new HashMap<>();
        HashMap<String, Object> whereMap_vehicleList = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start_Time = format.parse(startTime + " 00:00:00");
            Date end_Time = format.parse(endTime + " 23:59:59");

            if (null != vehicleID && vehicleID > 0) {
                whereMap.put("vehicle_id", vehicleID);
            }
            //业户待定
            if (null != enterprisseId && !"".equals(enterprisseId)) {
                param.put("enterprisseId", enterprisseId);
                List<String> vehicleIDList = this.selectList("PictureQuery.queryVehicleByUnitID", param);
                whereMap_vehicleList.put(QueryOperators.IN, vehicleIDList);
                whereMap.put("vehicle_id", whereMap_vehicleList);
            }
            if (null != startTime && !"".equals(startTime)) {
                whereMap_Time.put("$gte", start_Time);    //大于
            }
            if (null != endTime && !"".equals(endTime)) {
                whereMap_Time.put("$lte", end_Time);        //小于
            }
            if (null != eventCode && !"".equals(eventCode)) {
                List<String> eList = new ArrayList<>();
                Map<String, Object> eList_params = new HashMap<>();
                if (StringUtils.isNotEmpty(eventCode)) {
                    eList.add(eventCode);
                    eList = addEventCode(eList);
                }
                eList_params.put(QueryOperators.IN, eList);
                whereMap.put("eventCode", eList_params);
            }
            whereMap.put("gps_time", whereMap_Time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return whereMap;
    }

    /**
     * 查询更多
     *
     * @param vehicleId
     * @param startTime
     * @param endTime
     * @param pageSize
     * @param unitId
     * @param eventCode
     * @return
     */
    public List<HistoryImgVO> queryPictureListForMore(String vehicleId, String startTime, String endTime, String pageSize, String unitId, String eventCode) {
        HashMap<String, Object> paramFormatted = this.getParamFormatted(null, startTime, endTime, unitId, eventCode);
        int pageRecord = Integer.parseInt(pageSize);
        List<PictureVO> pictureImgList = new ArrayList<>();
        if (StringUtils.isNotEmpty(vehicleId)) {
            List<Integer> tempVehicleIds = new ArrayList<>();
            Map<String, Object> tempParamsIds = new HashMap<>();
            if (vehicleId.contains(",")) {
                String[] StringArrayIds = vehicleId.split(",");
                for (int i = 0; i < StringArrayIds.length; i++) {
                    tempVehicleIds.add(Integer.valueOf(StringArrayIds[i]));
                }
            } else {
                tempVehicleIds.add(Integer.valueOf(vehicleId));
            }
            tempParamsIds.put(QueryOperators.IN, tempVehicleIds);
            paramFormatted.put("vehicle_id", tempParamsIds);
        }
//        paramFormatted.put("pageSize", pageRecord);
        //sort
        Map<String, Object> sortMap = new HashMap<>();
        sortMap.put("gps_time", -1);
        List<HistoryImgVO> pics = MGTemplete.findForSkipSomeData("egov", "img_info", paramFormatted, sortMap, Integer.valueOf(pageSize), 30, HistoryImgVO.class, true);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (HistoryImgVO picVo : pics) {
            picVo.setGpsTimeStr(sdf.format(picVo.getGps_time()));
            picVo.setImgUrl(config.imagePath + ImgHelper.getImageFileName(picVo.getVehicle_id(), picVo.getLens_id(), picVo.getGps_time().getTime()));
        }
        //skip
//        for (HistoryImgVO vo : list) {
//            if (vo.getCoordinates().getCoordinates()[0] < 100) {// 经纬度为空，则去轨迹表数据
//                Map trackParamMap = new HashMap();
//                Date gpsTime = vo.getGps_time();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String dateStr = sdf.format(gpsTime);
//                trackParamMap.put("tableName", "gps_" + dateStr.substring(0, 10).replace("-", "_"));
//                trackParamMap.put("vehicleId", vo.getVehicleId());
//                trackParamMap.put("gpsTime", dateStr);
//                Map trackMap = (Map) this.selectOne("PictureQuery.queryLatestTrack", trackParamMap);
//                if (trackMap != null) {
//                    vo.setLongitude(Long.parseLong(trackMap.get("longitude").toString()));
//                    vo.setLatitude(Long.parseLong(trackMap.get("latitude").toString()));
//                    vo.setGpsSpeed(Float.parseFloat(trackMap.get("gps_speed").toString()));
//                    vo.setStatus(trackMap.get("status").toString());
//                }
//            }
//            // 状态解析
//            String statusstr = getStatusStr(vo.getTerminalKind(), vo.getStatus());
//            vo.setStatus(statusstr);
//            double latitude = (double) vo.getLatitude() / (double) 1000000;
//            double longitude = (double) vo.getLongitude() / (double) 1000000;
//            double[] gdLatlon = GpsToGaoDe.transform(latitude, longitude);
//            double gdLat = (int) (gdLatlon[0] * 1000000) / (double) 1000000;
//            double gdlng = (int) (gdLatlon[1] * 1000000) / (double) 1000000;
//            vo.setGdLat(gdLat);
//            vo.setGdLng(gdlng);
//            vo.setGpsTimeStr(dateFormat.format(vo.getGpsTime()));
//            String imgUrl = vo.getExtension();
//            if (imgUrl == null || imgUrl == "") {
////                imgUrl = Utils.formatImageFilename(vo.getTerminalID(), vo.getCameraNo(), vo.getGpsTime());
//            }
//            imgUrl = config.imagePath + imgUrl;
//            vo.setImgUrl(imgUrl);
//        }
        return pics;
    }


    public Map<String, Object> queryPictureByVehicleNoAndTime(String vehicleNo, Date gpsTime) {
        Map<String, Object> resultMap = new HashMap<>();
        HashMap<String, Object> whereMap = new HashMap<>();
        whereMap.put("vehicle_no", vehicleNo);
        whereMap.put("gps_time", gpsTime);
        List<MPictureVo> pictureVos = MGTemplete.find("egov", "img_info", whereMap, MPictureVo.class, true);
        //图片查看一张足够
        String imgName = null;
        if (pictureVos != null && pictureVos.size() != 0) {
            MPictureVo pictureVo = pictureVos.get(0);
            if (pictureVo.getMedia_format() == 0) { // 说明是图片
                imgName = ImgHelper.getImageFileName(pictureVo.getVehicle_id(), pictureVo.getLens_id(), pictureVo.getGps_time().getTime());
            }
            if (pictureVo.getMedia_format() == 5) { // 说明是视频
                imgName = ImgHelper.getImageFileName(pictureVo.getVehicle_id(), pictureVo.getLens_id(), pictureVo.getGps_time().getTime());
                imgName.replace(".jpg", ".mp4");
            }
            resultMap.put("imgUrl", config.imagePath + imgName);
            resultMap.put("mediaFormat", pictureVo.getMedia_format());
            resultMap.put("isHave", 1);
        } else {
            resultMap.put("imgUrl", "");
            resultMap.put("isHave", 0);
        }
        return resultMap;
    }

    /**
     * 查询报警类型
     *
     * @return
     */
    public List<Map<String, Object>> queryAlarmTypeForInitMap() {
        return this.selectList("PictureQuery.queryAlarmTypeForInitMap", null);
    }
}
